package com.newtouch.bxzs.business.message.component;

import com.newtouch.bxzs.business.message.mapper.NotificationMapper;
import com.newtouch.bxzs.business.message.mapper.NotificationUserMapMapper;
import com.newtouch.bxzs.business.message.websocket.service.WebsocketService;
import com.newtouch.bxzs.business.product.mapper.UserMapper;
import com.newtouch.bxzs.common.base.constant.RabbitMQConstant;
import com.newtouch.bxzs.common.base.em.NotificationTypeEnum;
import com.newtouch.bxzs.common.base.em.PublishStatusEnum;
import com.newtouch.bxzs.common.base.model.Notification;
import com.newtouch.bxzs.common.base.model.NotificationUserMap;
import com.newtouch.bxzs.common.base.model.bo.PushMessageBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * rabbitMQ 通知消息消费者
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/29 15:31</td>
 * <td>tianshangzhu</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author tianshangzhu
 * @version 1.0.0
 * @since 1.0.0
 */
@Component
@SuppressWarnings("unchecked")
public class ReceiveNotice {
    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(ReceiveNotice.class);

    @Autowired
    private WebsocketService websocketService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private NotificationUserMapMapper notificationUserMapMapper;

    @RabbitListener(queues = "${queue.topicNotice}")
    //@Transactional(rollbackFor = Exception.class)
    public void receive(Map<String, Object> msg) {
        logger.info("****业务通知消费者****接收到了：{}", msg);
        dealData(msg);
    }

    @RabbitListener(queues = "${queue.topicPcNotice}")
    //@Transactional(rollbackFor = Exception.class)
    public void receivePcNotice(Map<String, Object> msg) {
        logger.info("****后台通知消费者****接收到了：{}", msg);
        dealData(msg);
    }

    /**
     * 处理数据
     * @param msg
     */
    public void dealData(Map<String, Object> msg){
        List<String> userJobNumberList = new ArrayList<>();
        List<String> userIdList = new ArrayList<>();
        PushMessageBO messageBO = null;
        String notificationSubtype = null;
        String notificationId = null;
        Object obj = msg.get(RabbitMQConstant.USER_JOB_NUMBER_LIST_STR);
        Object obj2 = msg.get(RabbitMQConstant.USER_ID_LIST_STR);
        Object obj3 = msg.get(RabbitMQConstant.MESSAGE_STR);
        Object obj4 = msg.get(RabbitMQConstant.NOTIFICATION_SUB_TYPE_STR);
        Object obj5 = msg.get(RabbitMQConstant.NOTIFICATION_ID_STR);
        // 判断类型,是否工号
        if (obj instanceof List) {
            List<Object> list = (List<Object>) obj;
            for (Object item : list) {
                if (item instanceof String) {
                    userJobNumberList.add((String) item);
                }
            }
        }
        // 单个工号
        if (obj instanceof String) {
            userJobNumberList.add((String) obj);
        }

        // 用户id 集合
        if (obj2 instanceof List) {
            List<Object> list = (List<Object>) obj2;
            for (Object item : list) {
                if (item instanceof String) {
                    userIdList.add((String) item);
                }
            }
        }

        // 单个用户id
        if (obj2 instanceof String) {
            userIdList.add((String) obj2);
        }

        // 消息实体
        if (obj3 instanceof PushMessageBO) {
            messageBO = (PushMessageBO) obj3;
        }

        // 消息子类型
        if(obj4 instanceof String){
            notificationSubtype = (String) obj4;
        }
        // 通知id
        if (obj5 instanceof String) {
            notificationId = (String) obj5;
        }
        // 如果userIdList为空，根据用户工号查询
        if(userIdList.isEmpty() &&  !userJobNumberList.isEmpty()){
            userIdList = listUserIdByUserJobNumberList(userJobNumberList);
        }
        // 如果通知id为null,先维护通知信息表
        if(notificationId == null && messageBO != null){
            // 通知消息入库
            notificationId = this.insertIntoNotification(messageBO, notificationSubtype);
        }
        // 维护通知用户中间表，websocket推送
        if (!userIdList.isEmpty() && messageBO != null) {
            // 通知用户中间表入库
            this.insertToNotificationUserMap(notificationId,userIdList);
            // 实现websocket推送
            websocketService.send2Users(userIdList, messageBO);
        }
        logger.info("消息队列处理完毕");
    }

    /**
     * 根据用户工号查询用户id
     *
     * @param userJobNumberList 用户公号集合
     * @return 用户id集合
     */
    public List<String> listUserIdByUserJobNumberList(List<String> userJobNumberList) {
        return userMapper.listUserIdByUserJobNumberList(userJobNumberList);
    }


    /**
     * 通知消息入库
     * @return 消息id
     */
    public String insertIntoNotification(PushMessageBO message,String notificationSubtype){
        Notification notification = new Notification( );
        notification.setNotificationName(message.getTitle());
        notification.setNotificationType(NotificationTypeEnum.NOTIFICATION_BUSINESS_TYPE.getResultCode());
        notification.setNotificationSubtype(notificationSubtype);
        notification.setNotificationContent(message.getContent());
        notification.setPublishTime(new Date());
        // 状态为已发布
        notification.setPublishStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
        // notification.setCreateUserId(UserDetailUtil.getUserDetail()== null? null:UserDetailUtil.getUserDetail().getUserId());
        notification.setCreateTime(new Date());
        notification.setDeleteFlag(false);
        notification.setMemo(message.getNoticeJumpId()+","+message.getPolicyNoticeType()+","+message.getPolicyType()+","+message.getUnifiedSocialCreditCode());
        // 插入通知表
        notificationMapper.insert(notification);
        logger.info("通知消息表插入完成");
        return notification.getNotificationId();
    }

    /**
     * 处维护通知用户关系表
     * @param notificationId 通知id
     * @param userIds 接收用户id集合
     */
    public void insertToNotificationUserMap(String notificationId,List<String> userIds){
        List<NotificationUserMap> list = new ArrayList<>();

        Date date = new Date();
        // 遍历接收用户
        for (String userId : userIds) {
            // 封装NotificationUserMap
            NotificationUserMap notificationUserMap = new NotificationUserMap();
            notificationUserMap.setNotificationId(notificationId);
            notificationUserMap.setUserId(userId);
            notificationUserMap.setReadFlag(false);
            // notificationUserMap.setCreateUserId(UserDetailUtil.getUserDetail()== null? null:UserDetailUtil.getUserDetail().getUserId());
            notificationUserMap.setCreateTime(date);
            notificationUserMap.setDeleteFlag(false);
            list.add(notificationUserMap);
        }
        // 批量插入
        notificationUserMapMapper.saveBatch(list);
        logger.info("通知用户中间表插入完成");
    }
}
